{% extends 'base.html' %}

{% block title %}设备列表 - Allen监控系统{% endblock %}

{% block content %}
<div class="card">
    <!-- 在 card div 的开始位置添加 CSRF token -->
    {% csrf_token %}
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">设备列表</h5>
        <div>
            <!-- 添加批量操作和导入导出按钮 -->
            <div class="btn-group me-2">
                <button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                    批量操作
                </button>
                <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="#" id="batchDelete">批量删除</a></li>
                    <li><a class="dropdown-item" href="#" id="batchEnable">批量启用</a></li>
                    <li><a class="dropdown-item" href="#" id="batchDisable">批量禁用</a></li>
                </ul>
            </div>
            <div class="btn-group me-2">
                <button class="btn btn-success dropdown-toggle" type="button" data-bs-toggle="dropdown">
                    导入/导出
                </button>
                <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="{% url 'export_hosts' %}">导出设备列表</a></li>
                    <li><a class="dropdown-item" href="{% url 'import_hosts' %}">导入设备</a></li>
                    <li><a class="dropdown-item" href="{% url 'download_template' %}">下载导入模板</a></li>
                </ul>
            </div>
            <!-- 自动发现按钮 -->
            <a href="{% url 'auto_discover' %}" class="btn btn-info me-2">自动发现</a>
            <!-- 添加设备按钮带下拉菜单 -->
            <div class="btn-group">
                <button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                    添加设备
                </button>
                <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="{% url 'host_add' %}?type=ipmi">添加IPMI设备</a></li>
                    <li><a class="dropdown-item" href="{% url 'host_add' %}?type=snmp">添加SNMP设备</a></li>
                </ul>
            </div>
        </div>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th><input type="checkbox" id="selectAll"></th>
                        <th>主机名</th>
                        <th>IP地址</th>
                        <th>监控类型</th>
                        <th>状态</th>
                        <th>CPU使用率</th>
                        <th>内存使用率</th>
                        <th>磁盘使用率</th>
                        <th>最后更新</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for host in hosts %}
                    <tr data-host-id="{{ host.id }}" class="host-row">
                        <td><input type="checkbox" class="host-select" value="{{ host.id }}"></td>
                        <td>{{ host.hostname }}</td>
                        <td>{{ host.ip_address }}</td>
                        <td>{{ host.get_monitor_type_display }}</td>
                        <td>
                            <span class="badge {% if host.status == 'enabled' %}bg-success
                                           {% elif host.status == 'disabled' %}bg-secondary
                                           {% else %}bg-danger{% endif %}">
                                {{ host.get_status_display }}
                            </span>
                        </td>
                        <td class="cpu-usage">
                            {% if host.snmp_cpu_usage is not None %}
                            <div class="progress" style="height: 20px; background-color: #f8f9fa; position: relative;">
                                <div class="progress-bar progress-bar-striped" role="progressbar" 
                                     style="width: {{ host.snmp_cpu_usage }}%;
                                            {% if host.snmp_cpu_usage > 90 %}
                                            background-color: #dc3545;
                                            {% elif host.snmp_cpu_usage > 70 %}
                                            background-color: #ffc107;
                                            {% else %}
                                            background-color: #198754;
                                            {% endif %}"
                                     aria-valuenow="{{ host.snmp_cpu_usage }}" 
                                     aria-valuemin="0" aria-valuemax="100">
                                </div>
                                <div style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; 
                                            display: flex; align-items: center; justify-content: center;
                                            color: #000; text-shadow: 1px 1px 2px rgba(255,255,255,0.5);">
                                    {{ host.snmp_cpu_usage|floatformat:1 }}%
                                </div>
                            </div>
                            {% else %}
                            --
                            {% endif %}
                        </td>
                        <td class="memory-usage">
                            {% if host.snmp_memory_usage is not None %}
                            <div class="progress" style="height: 20px; background-color: #f8f9fa; position: relative;">
                                <div class="progress-bar progress-bar-striped" role="progressbar" 
                                     style="width: {{ host.snmp_memory_usage }}%;
                                            {% if host.snmp_memory_usage > 90 %}
                                            background-color: #dc3545;
                                            {% elif host.snmp_memory_usage > 70 %}
                                            background-color: #ffc107;
                                            {% else %}
                                            background-color: #198754;
                                            {% endif %}"
                                     aria-valuenow="{{ host.snmp_memory_usage }}" 
                                     aria-valuemin="0" aria-valuemax="100">
                                </div>
                                <div style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; 
                                            display: flex; align-items: center; justify-content: center;
                                            color: #000; text-shadow: 1px 1px 2px rgba(255,255,255,0.5);">
                                    {{ host.snmp_memory_usage|floatformat:1 }}%
                                </div>
                            </div>
                            {% else %}
                            --
                            {% endif %}
                        </td>
                        <td class="disk-usage">
                            {% if host.snmp_disk_usage is not None and host.snmp_disk_usage >= 0 %}
                            <div class="progress" style="height: 20px; background-color: #f8f9fa; position: relative;">
                                <div class="progress-bar progress-bar-striped" role="progressbar" 
                                     style="width: {{ host.snmp_disk_usage }}%;
                                            {% if host.snmp_disk_usage > 90 %}
                                            background-color: #dc3545;
                                            {% elif host.snmp_disk_usage > 70 %}
                                            background-color: #ffc107;
                                            {% else %}
                                            background-color: #198754;
                                            {% endif %}"
                                     aria-valuenow="{{ host.snmp_disk_usage }}" 
                                     aria-valuemin="0" aria-valuemax="100">
                                </div>
                                <div style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; 
                                            display: flex; align-items: center; justify-content: center;
                                            color: #000; text-shadow: 1px 1px 2px rgba(255,255,255,0.5);">
                                    {{ host.snmp_disk_usage|default:0|floatformat:1 }}%
                                </div>
                            </div>
                            {% else %}
                            --
                            {% endif %}
                        </td>
                        <td class="last-update">
                            {{ host.snmp_last_update|date:"Y-m-d H:i:s"|default:"--" }}
                        </td>
                        <td>
                            <div class="btn-group">
                                <a href="{% url 'host_edit' host.id %}" class="btn btn-sm btn-primary">编辑</a>
                                <button type="button" class="btn btn-sm btn-info update-metrics" 
                                        data-host-id="{{ host.id }}">
                                    更新
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="8" class="text-center">暂无设备</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>
{% endblock %} 

<!-- 添加必要的JavaScript -->
{% block extra_js %}
<script>
    $(document).ready(function() {
        // 排序功能
        $('.sortable').click(function() {
            const sort_by = $(this).data('sort');
            const current_url = new URL(window.location.href);
            current_url.searchParams.set('sort_by', sort_by);
            window.location.href = current_url.toString();
        });

        function updateHostRow(hostId, newStatus) {
            const row = $(`tr[data-host-id="${hostId}"]`);
            const statusCell = row.find('.status-cell');
            
            // 更新状态显示
            if (newStatus === 'enabled') {
                statusCell.html('<span class="badge bg-success">启用</span>');
            } else if (newStatus === 'disabled') {
                statusCell.html('<span class="badge bg-secondary">禁用</span>');
            }
        }

        function batchOperation(action) {
            const selected = $('.host-select:checked').map(function() {
                return $(this).val();
            }).get();

            if (selected.length === 0) {
                alert('请先选择要操作的设备');
                return;
            }

            const csrfToken = $('[name=csrfmiddlewaretoken]').val();
            
            // 禁用按钮，显示加载状态
            $('#batchEnable, #batchDisable').prop('disabled', true);
            
            $.ajax({
                url: "{% url 'batch_update_hosts' %}",
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    host_ids: selected,
                    action: action
                }),
                headers: {
                    'X-CSRFToken': csrfToken
                },
                success: function(response) {
                    if (response.status === 'success') {
                        // 更新页面统计数据
                        $('#hostCount').text(response.data.host_count);
                        $('#disabledCount').text(response.data.disabled_count);
                        $('#totalHosts').text(response.data.total_hosts);
                        $('#onlineRate').text(response.data.online_rate + '%');
                        
                        // 更新每个选中行的状态
                        selected.forEach(hostId => {
                            updateHostRow(hostId, action);
                        });
                        
                        // 取消所有选中状态
                        $('.host-select').prop('checked', false);
                        $('#selectAll').prop('checked', false);
                        
                        // 显示成功消息
                        alert(response.message);
                    } else {
                        alert('操作失败：' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    alert('操作失败：' + error);
                },
                complete: function() {
                    // 恢复按钮状态
                    $('#batchEnable, #batchDisable').prop('disabled', false);
                }
            });
        }

        // 批量启用按钮点击事件
        $('#batchEnable').click(function() {
            if(confirm('确定要启用选中的设备吗？')) {
                batchOperation('enable');
            }
        });

        // 批量禁用按钮点击事件
        $('#batchDisable').click(function() {
            if(confirm('确定要禁用选中的设备吗？')) {
                batchOperation('disable');
            }
        });

        // 全选功能
        $('#selectAll').change(function() {
            $('.host-select').prop('checked', $(this).prop('checked'));
        });

        // 更新单个主机的监控数据
        function updateHostMetrics(hostId) {
            const row = $(`tr[data-host-id="${hostId}"]`);
            const updateBtn = row.find('.update-metrics');
            
            // 禁用更新按钮并显示加载状态
            updateBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');
            
            $.ajax({
                url: '{% url "host_list" %}',
                data: { host_id: hostId },
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                },
                success: function(response) {
                    if (response.status === 'success') {
                        const data = response.data;
                        
                        // 更新CPU使用率
                        if (data.cpu_usage !== null) {
                            const bgColor = data.cpu_usage > 90 ? '#dc3545' : 
                                            data.cpu_usage > 70 ? '#ffc107' : '#198754';
                            row.find('.cpu-usage').html(`
                                <div class="progress" style="height: 20px; background-color: #f8f9fa; position: relative;">
                                    <div class="progress-bar progress-bar-striped" role="progressbar" 
                                         style="width: ${data.cpu_usage}%; background-color: ${bgColor};"
                                         aria-valuenow="${data.cpu_usage}" 
                                         aria-valuemin="0" aria-valuemax="100">
                                    </div>
                                    <div style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; 
                                                display: flex; align-items: center; justify-content: center;
                                                color: #000; text-shadow: 1px 1px 2px rgba(255,255,255,0.5);">
                                        ${data.cpu_usage.toFixed(1)}%
                                    </div>
                                </div>
                            `);
                        }
                        
                        // 更新内存使用率
                        if (data.memory_usage !== null) {
                            const bgColor = data.memory_usage > 90 ? '#dc3545' : 
                                            data.memory_usage > 70 ? '#ffc107' : '#198754';
                            row.find('.memory-usage').html(`
                                <div class="progress" style="height: 20px; background-color: #f8f9fa; position: relative;">
                                    <div class="progress-bar progress-bar-striped" role="progressbar" 
                                         style="width: ${data.memory_usage}%; background-color: ${bgColor};"
                                         aria-valuenow="${data.memory_usage}" 
                                         aria-valuemin="0" aria-valuemax="100">
                                    </div>
                                    <div style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; 
                                                display: flex; align-items: center; justify-content: center;
                                                color: #000; text-shadow: 1px 1px 2px rgba(255,255,255,0.5);">
                                        ${data.memory_usage.toFixed(1)}%
                                    </div>
                                </div>
                            `);
                        }
                        
                        // 更新磁盘使用率
                        if (data.disk_usage !== null && data.disk_usage >= 0) {
                            const bgColor = data.disk_usage > 90 ? '#dc3545' : 
                                            data.disk_usage > 70 ? '#ffc107' : '#198754';
                            row.find('.disk-usage').html(`
                                <div class="progress" style="height: 20px; background-color: #f8f9fa; position: relative;">
                                    <div class="progress-bar progress-bar-striped" role="progressbar" 
                                         style="width: ${data.disk_usage}%; background-color: ${bgColor};"
                                         aria-valuenow="${data.disk_usage}" 
                                         aria-valuemin="0" aria-valuemax="100">
                                    </div>
                                    <div style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; 
                                                display: flex; align-items: center; justify-content: center;
                                                color: #000; text-shadow: 1px 1px 2px rgba(255,255,255,0.5);">
                                        ${(data.disk_usage || 0).toFixed(1)}%
                                    </div>
                                </div>
                            `);
                        } else {
                            row.find('.disk-usage').html('--');
                        }
                        
                        // 更新最后更新时间
                        row.find('.last-update').text(data.last_update);
                    } else {
                        alert('更新失败：' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    alert('更新失败：' + error);
                },
                complete: function() {
                    // 恢复更新按钮状态
                    updateBtn.prop('disabled', false).text('更新');
                }
            });
        }

        // 绑定更新按钮点击事件
        $('.update-metrics').click(function() {
            const hostId = $(this).data('host-id');
            updateHostMetrics(hostId);
        });

        // 可选：定期自动更新
        setInterval(function() {
            $('.host-row').each(function() {
                const hostId = $(this).data('host-id');
                updateHostMetrics(hostId);
            });
        }, 300000); // 每5分钟更新一次
    });
</script>
{% endblock %}
